<template>
  <div>
    <el-drawer
      v-model="dialogFormVisible"
      v-loading="loading"
      :title="title"
      direction="rtl"
      size="70%"
      @close="close"
    >
      <el-form
        ref="formRef"
        v-loading="loading"
        label-width="100px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="选择任务类型" prop="name">
          <el-checkbox
            v-for="(item, index) in jobTypeList"
            :key="index"
            v-model="checkedOptions[item.id]"
            :label="item.name"
            border
            @change="change"
          />
        </el-form-item>
      </el-form>
      <el-row>
        <el-col
          v-for="(item, index) in checkedJobTypeShowList"
          :key="index"
          :span="7"
          :offset="index % 3 == 0 ? 0 : 1"
        >
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>{{ item.name }}</span>
              </div>
            </template>
            <el-form :model="item.form" label-width="100px">
              <el-form-item label="选择任务执行人">
                <el-select
                  v-model="item.form.boyi_to_uid"
                  clearable
                  filterable
                  placeholder="请选择任务执行人"
                >
                  <el-option
                    v-for="(item1, index1) in userList"
                    :key="index1"
                    :label="item1.name"
                    :value="item1.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="任务佣金">
                <el-input v-model="item.form.amount" type="number" />
              </el-form-item>
              <el-form-item label="任务备注">
                <el-input v-model="item.form.remark" type="textarea" />
              </el-form-item>
              <el-form-item label="截止日期">
                <el-date-picker
                  v-model="item.form.diedline"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD 23:59:59"
                  :shortcuts="shortcuts"
                  placeholder="截止日期"
                />
              </el-form-item>
              <el-form-item label="任务附件">
                <el-upload
                  v-model:file-list="item.form.fileList"
                  class="upload-demo"
                  multiple
                  :action="baseURL + '/api/file/file'"
                  :on-change="handleChange"
                >
                  <el-button type="primary">点击选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      请上传文件附件，大小不超过10M
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <div style="text-align: center">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
  import { batchAddUserJob } from '@/api/boyiJob'

  import { baseURL } from '@/config'

  export default defineComponent({
    name: 'AssignJob',
    props: {
      jobTypeList: {
        type: Array,
        default: () => [],
      },
      userList: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const shortcuts = [
        {
          text: '今天',
          value: new Date(),
        },
        {
          text: '明天',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            return date
          },
        },
        {
          text: '一周后',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            return date
          },
        },
      ]

      const state = reactive({
        formRef: null,
        form: {},
        customer: {},
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        },
        title: '',
        checkedOptions: [],
        checkedJobTypeList: [],
        checkedJobTypeShowList: [],
        dialogFormVisible: false,
        loading: false,
        baseURL: baseURL,
        shortcuts: shortcuts,
      })

      const showEdit = (row) => {
        console.log(state.checkedOptions)
        state.title = '指派任务'
        state.customer = Object.assign({}, row)
        state.dialogFormVisible = true
      }

      const handleChange = () => {
        console.log(state.checkedJobTypeShowList)
      }

      const change = () => {
        // 遍历出被选中的任务类型列表
        const checkedJobTypeList = state.checkedJobTypeList
        for (const key in state.checkedOptions) {
          if (state.checkedOptions[key]) {
            // 这里要匹配出任务类型jobTypeList的数据
            const is_exist = checkedJobTypeList.some((item) => {
              return item.id == key
            })

            if (is_exist) {
              checkedJobTypeList.forEach((item, index) => {
                if (item.id == key) {
                  checkedJobTypeList[index]['checked'] = true
                }
              })
            } else {
              props.jobTypeList.find((item) => {
                if (item.id == key) {
                  item.form = {
                    amount: item.amount,
                  }
                  item.checked = true
                  checkedJobTypeList.push(item)
                }
              })
            }
          } else {
            checkedJobTypeList.forEach((item, index) => {
              if (item.id == key) {
                checkedJobTypeList[index]['checked'] = false
              }
            })
          }
        }

        state.checkedJobTypeList = checkedJobTypeList

        // 下面是为了避免在页面上同时使用v-for v-if
        const checkedJobTypeShowList = []
        checkedJobTypeList.forEach((item) => {
          if (item.checked) {
            checkedJobTypeShowList.push(item)
          }
        })
        state.checkedJobTypeShowList = checkedJobTypeShowList
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.checkedJobTypeList = []
        state.checkedJobTypeShowList = []

        for (const key in state.checkedOptions) {
          state.checkedOptions[key] = false
        }
        state.dialogFormVisible = false
      }
      const save = async () => {
        console.log(state.checkedJobTypeShowList)
        let post_data = []

        if (state.checkedJobTypeShowList.length == 0) {
          $baseMessage(
            `请先选择需要指派的任务`,
            'error',
            'vab-hey-message-error'
          )
          return false
        }

        state.checkedJobTypeShowList.some((element) => {
          const tmp_data = {}

          if (!element.form.boyi_to_uid) {
            $baseMessage(
              `请选择【${element.name}】任务执行人`,
              'error',
              'vab-hey-message-error'
            )
            post_data = []
            return false
          }
          if (!element.form.diedline) {
            $baseMessage(
              `请选择【${element.name}】任务截止日期`,
              'error',
              'vab-hey-message-error'
            )
            post_data = []
            return false
          }

          if (element.form.amount == '') {
            $baseMessage(
              `请选择【${element.name}】任务佣金`,
              'error',
              'vab-hey-message-error'
            )
            post_data = []
            return false
          }

          tmp_data['job_type_id'] = element.id
          tmp_data['boyi_to_uid'] = element.form.boyi_to_uid
          tmp_data['diedline'] = element.form.diedline
          tmp_data['customer_id'] = state.customer.id

          // element.tmp_data['file_id_list'] = status.customer.id
          const file_id_list = []
          if (element.form.fileList) {
            element.form.fileList.forEach((item) => {
              file_id_list.push(item.response.data.id)
            })
          }
          tmp_data['amount'] = element.form.amount
          tmp_data['file_id_list'] = file_id_list
          // tmp_data['customer_id'] = element.boyi_to_uid
          post_data.push(tmp_data)
        })
        if (post_data.length > 0) {
          // console.log(result)
          // console.log('-----')
          // console.log(post_data)
          state.loading = true

          try {
            const { msg } = await batchAddUserJob({
              job_json: JSON.stringify(post_data),
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
          } catch (error) {
            console.log(error)
          }

          emit('fetch-data')
          state.loading = true
          close()
        }
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        change,
        handleChange,
        save,
      }
    },
  })
</script>
